package blog.spring.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;

import blog.spring.db.service.IArticleService;
import blog.spring.db.service.ICommentService;
import blog.spring.db.service.IGlobalService;
import blog.spring.db.service.IUserService;
import blog.spring.web.util.CookieUtils;

@Controller()
public class ApplicationController {

	@Resource
	private IUserService userService;
	@Resource
	private IArticleService articleService;
	@Resource
	IGlobalService globalService;
	@Resource
	private ICommentService commentService;

	@RequestMapping(value = "/*", method = RequestMethod.GET)
	public String index(ModelMap map) {
		map.addAttribute("articleInfos", articleService.indexList(1));
		map.addAttribute("hotArticles", articleService.findHot(5));
		map.addAttribute("newComments", commentService.findNew(5));
		return "index";
	}

	@RequestMapping(value = "/page/{pageIndex}", method = RequestMethod.GET)
	public String index(@PathVariable("pageIndex") Integer pageIndex,
			ModelMap map) {
		if (pageIndex == null || pageIndex <= 0)
			return "redirect:/";
		map.addAttribute("articleInfos", articleService.indexList(pageIndex));
		map.addAttribute("hotArticles", articleService.findHot(5));
		map.addAttribute("newComments", commentService.findNew(5));
		map.addAttribute("pageIndex", pageIndex);
		return "index";
	}

	// 临时后台
	@RequestMapping(value = "/sysindex", method = RequestMethod.GET)
	public String sysIndex(ModelMap map, HttpServletRequest req) {
		map.addAttribute("articleInfos",
				articleService.findList(1, 15, null, null));
		map.addAttribute("user", CookieUtils.isLogin(req, userService));
		return "sys_index";
	}

	// 页眉
	@RequestMapping(value = "/header")
	public String header(ModelMap map, HttpServletRequest req) {
		req.getServletContext().setAttribute("global",
				globalService.findById(1));
		map.addAttribute("user", CookieUtils.isLogin(req, userService));
		return "public/header";
	}

	// 页脚
	@RequestMapping(value = "/footer")
	public String footer(ModelMap map) {
		return "public/footer";
	}
}
